package br.ufc.vv.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import br.ufc.vv.model.Usuario;
import br.ufc.vv.util.HibernateUtil;

public class UsuarioDao {

	
	public void save(Usuario aluno){
		Session session = HibernateUtil.getSession();
		Transaction transacao = session.beginTransaction();
		try {
			session.save(aluno);
			transacao.commit();
		} catch (Exception e) {
			transacao.rollback();
		} finally {
			session.close();
		}	
	}
	
	
	public void update(Usuario aluno){
		Session session = HibernateUtil.getSession();
		Transaction transacao = session.beginTransaction();
		try {
			session.update(aluno);
			transacao.commit();
		} catch (Exception e) {
			transacao.rollback();
		} finally {
			session.close();
		}	
	}
	
	public void delete(Usuario aluno){
		Session session = HibernateUtil.getSession();
		Transaction transacao = session.beginTransaction();
		try {
			session.delete(aluno);
			transacao.commit();
		} catch (Exception e) {
			transacao.rollback();
		} finally {
			session.close();
		}	
	}
	
	public List<Usuario> list(){
		Session session = HibernateUtil.getSession();
		try {
			Criteria c = session.createCriteria(Usuario.class);
			return c.list();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
		return null;
	}

	public Usuario get(Long id) {
		Session session = HibernateUtil.getSession();
			return (Usuario) session.get(Usuario.class, id);
		
	}
	
	public Usuario logar(Usuario usuario){
		Session session = HibernateUtil.getSession();
		try {
			Criteria c = session.createCriteria(Usuario.class);
			c.add(Restrictions.eq("email", usuario.getE_mail()));
			c.add(Restrictions.eq("senha", usuario.getSenha()));
			return (Usuario) c.uniqueResult();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
		return null;
	}
}
